package org.example;

import java.util.Arrays;

public class Test2 {
    //leetcode 最长公共前缀 https://leetcode.cn/problems/longest-common-prefix/description/?envType=study-plan-v2&envId=top-interview-150
    public String longestCommonPrefix(String[] strs) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < strs[0].length(); i++) {
            char c = strs[0].charAt(i);
            for (int j = 1; j < strs.length; j++) {
                if (i >= strs[j].length() || strs[j].charAt(i) != c) return sb.toString();
            }
            sb.append(c);
        }
        return sb.toString();
    }

    /**
     * 将数组中的字符串按照字典序排序，然后只用比较第一个元素和最后一个元素就可以得到最终的答案
     * @param strs
     * @return
     */
    public String longestCommonPrefix1(String[] strs) {
        Arrays.sort(strs);
        int index = 0,len = strs.length;
        for (; index < strs[0].length();index++) {
            if (strs[0].charAt(index) != strs[len-1].charAt(index)) break;
        }
        return strs[0].substring(0,index);
    }

    public static void main(String[] args) {
        Test2 test2 = new Test2();
        String[] arr = {"flower","flow","flight"};
        test2.longestCommonPrefix1(arr);
        System.out.println(555);
    }
}
